<template>
  <div class="modal-overlay" v-if="visible" @click="handleClose">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>留下您的需求，我们会尽快与您联系</h3>
        <button class="close-btn" @click="handleClose">×</button>
        <!-- 恢复关闭按钮 -->
      </div>

      <form class="demand-form" @submit.prevent="handleSubmit">
        <div class="form-row">
          <div class="form-group">
            <label for="visitorName">* 名称：</label>
            <input type="text" id="visitorName" v-model="formData.visitorName" placeholder="请输入您的姓名" required />
          </div>
          <div class="form-group">
            <label for="mobile">* 联系电话：</label>
            <input type="tel" id="mobile" v-model="formData.mobile" placeholder="请输入您的联系电话" required />
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="companyName">* 公司名称：</label>
            <input type="text" id="companyName" v-model="formData.companyName" placeholder="请输入公司名称" required />
          </div>
          <div class="form-group">
            <label for="duty">* 职务：</label>
            <input type="text" id="duty" v-model="formData.duty" placeholder="请输入您的职务" required />
          </div>
        </div>

        <div class="form-group">
          <label for="startTime">* 试用时间：</label>
          <div class="date-input-container">
            <img src="@/assets/img/icon/calendar.png" alt="选择日期" class="calendar-icon" @click="openDatePicker" />
            <input
              type="text"
              id="startTime"
              ref="dateInput"
              v-model="formData.startTime"
              required
              @click="openDatePicker"
            />
          </div>
        </div>

        <div class="form-group">
          <label for="demandDescription">* 需求描述：</label>
          <textarea
            id="demandDescription"
            v-model="formData.demandDescription"
            placeholder="请输入您的需求描述..."
            rows="4"
            maxlength="200"
            required
          ></textarea>
          <p class="char-count">{{ formData.demandDescription.length }}/200</p>
        </div>

        <div class="form-group agree-terms">
          <input type="checkbox" id="agreePrivacy" v-model="formData.agreePrivacy" required />
          <label for="agreePrivacy"> 我已阅读并同意《<a href="#" target="_blank">隐私政策申明</a>》 </label>
        </div>

        <button type="submit" class="submit-btn">立即提交</button>
      </form>
    </div>
  </div>
</template>

<script>
import flatpickr from 'flatpickr';
// import { visitorApplyUsingPost } from '@/api/front/apIfangke';

export default {
  name: 'DemandModal',
  props: {
    // 控制弹窗显示与隐藏
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        visitorName: '',
        mobile: '',
        companyName: '',
        duty: '',
        startTime: '',
        demandDescription: '',
        agreePrivacy: false
      },
      datePickerInstance: null
    };
  },
  watch: {
    // 监听visible变化，初始化或销毁日期选择器
    visible(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.initDatePicker();
        });
      } else {
        this.destroyDatePicker();
      }
    }
  },
  methods: {
    // 初始化日期选择器
    initDatePicker() {
      if (this.datePickerInstance || !this.$refs.dateInput) return;

      this.datePickerInstance = flatpickr(this.$refs.dateInput, {
        dateFormat: 'Y-m-d',
        onClose: (selectedDates) => {
          if (selectedDates.length) {
            this.formData.startTime = selectedDates[0].toISOString().split('T')[0];
          }
        }
      });
    },

    // 打开日期选择器
    openDatePicker() {
      if (this.datePickerInstance) {
        this.datePickerInstance.open();
      }
    },

    // 销毁日期选择器实例
    destroyDatePicker() {
      if (this.datePickerInstance) {
        this.datePickerInstance.destroy();
        this.datePickerInstance = null;
      }
    },

    // 提交表单
    handleSubmit() {
      // 简单表单验证
      if (!this.formData.visitorName || !this.formData.mobile || !this.formData.companyName ||
        !this.formData.duty || !this.formData.startTime || !this.formData.demandDescription ||
        !this.formData.agreePrivacy) {
        alert('请填写完整表单信息并同意隐私政策');
        return;
      }
      console.log('提交的表单数据:', this.formData);


      // 提交表单数据，调用实际API
      // visitorApplyUsingPost({ body: this.formData }).then(res => {
      //   if (res.success === true) {
      //     const item = String(res.data);
      //     // 正则匹配手机号
      //     if (item.match("0?1[0-9]{10}")) {
      //       localStorage.setItem('mobile', item);
      //       this.$message.success('正在跳转至算法试用页面...');
      //       setTimeout(() => {
      //         this.$router.push({ path: `/algorithmApply` });
      //       }, 2000);
      //       this.handleClose(); // 跳转前关闭弹窗
      //       return;
      //     }
      //     this.$message.success('提交成功！');
      //     this.handleClose(); // 提交成功后关闭弹窗
      //   } else {
      //     this.$message.error('提交失败！' + res.msg);
      //   }
      // }).catch(err => {
      //   this.$message.error('接口请求失败，请稍后重试');
      //   console.error('提交错误:', err);
      // });
    },

    // 关闭弹窗（触发父组件事件+重置表单）
    handleClose() {
      // console.log('关闭弹窗');
      this.$emit('update:visible', false); // 通知父组件隐藏弹窗
      this.resetForm();    // 重置表单数据
    },

    // 重置表单
    resetForm() {
      this.formData = {
        visitorName: '',
        mobile: '',
        companyName: '',
        duty: '',
        startTime: '',
        demandDescription: '',
        agreePrivacy: false
      };
    }
  },
  beforeDestroy() {
    this.destroyDatePicker(); // 组件销毁前清理日期选择器
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  pointer-events: auto;
  /* 恢复遮罩层点击事件，允许点击关闭 */
}

.modal-content {
  background-color: #fff;
  width: 500px;
  max-width: 90%;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
  pointer-events: auto;
  /* 确保弹窗内部元素可正常点击 */
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  margin-left: 110px;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  line-height: 1;
  display: block;
  /* 恢复关闭按钮显示 */
}

.close-btn:hover {
  color: #333;
  /* hover效果优化，提升交互体验 */
}

/* 以下样式保持不变，确保表单布局和交互正常 */
.demand-form {
  display: flex;
  flex-direction: column;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 6px;
  font-size: 14px;
  color: #666;
}

.form-group input,
.form-group textarea {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: none;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin: 4px 0 0 0;
}

.agree-terms {
  flex-direction: row;
  align-items: center;
  margin: 10px 0 20px;
  font-size: 14px;
}

.agree-terms input {
  margin-right: 8px;
  width: auto;
}

.agree-terms a {
  color: #00af82;
  text-decoration: none;
}

.agree-terms a:hover {
  text-decoration: underline;
}

.submit-btn {
  background-color: #00af82;
  color: #fff;
  border: none;
  padding: 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  width: 100%;
}

.submit-btn:hover {
  background-color: #009670;
}

.date-input-container {
  position: relative;
  display: flex;
  align-items: center;
}

.calendar-icon {
  position: absolute;
  left: 10px;
  width: 16px;
  height: 16px;
  cursor: pointer;
  z-index: 1;
}

#startTime {
  padding-left: 36px !important;
}
</style>